package com.yncmcc.Repository;

import com.yncmcc.Entity.UserEntity;
import com.yncmcc.Repository.Interface.UserRepositoryCustom;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.*;

/**
 * Created by CMCC-Sunmo on 2016/9/21.
 */
public class UserRepositoryImpl implements UserRepositoryCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<UserEntity> findUser(UserEntity userEntity) {
        List<Short> right = new ArrayList<Short>();

        if(userEntity.getUserName() == ""){
            userEntity.setUserName(null);
        }

        if(userEntity.getDeptId().equals("0")){
            userEntity.setDeptId(null);
        }

        if(userEntity.getUserRight() == null)
        {
            right.add((Short) (short) 1);
            right.add((Short) (short) 2);
            right.add((Short) (short) 3);
        }else {
            if (userEntity.getUserRight() == 1) {
                right.add((Short) (short) 1);
            } else if (userEntity.getUserRight() == 2) {
                right.add((Short) (short) 2);
            } else if (userEntity.getUserRight() == 3) {
                right.add((Short) (short) 3);
            }
        }
        List<UserEntity> userEntities = entityManager.createNativeQuery(
                "SELECT * " +
                "FROM user u " +
                "WHERE 1 = 1 " +
                "and u.userStatus = 1 " +
                "and u.userName like :userName " +
                "and u.deptID like :deptID " +
                "and u.userFullName like :userFullName " +
                "and u.userRight in :userRight " +
                "order by u.userRight, u.deptID, u.userName", UserEntity.class)
                .setParameter("userName", (userEntity.getUserName() != null) ? "%" + userEntity.getUserName() + "%" : "%%")
                .setParameter("deptID", (userEntity.getDeptId() != null) ? "%" + userEntity.getDeptId() + "%" : "%%")
                .setParameter("userFullName", (userEntity.getUserFullName() != null) ? "%" + userEntity.getUserFullName() + "%" : "%%")
                .setParameter("userRight", right)
                .getResultList();


        return userEntities;

    }
}
